package service

import (
	"dao"
	"pojo/form"
	"pojo/model"
	"util"

	"github.com/jinzhu/gorm"
	"constant"
	"pojo/vo"
)

// 管理员服务层
type AdminService struct {
	dao *dao.AdminDao
}

// 构造管理员服务层
func NewAdminService(dao *dao.AdminDao) *AdminService {

	return &AdminService{
		dao: dao,
	}
}

// 保存管理员信息
func (this *AdminService) InsertAdmin(adminForm *form.AdminForm) (*model.Admin, error) {

	_, err := this.dao.GetAdmin(adminForm.Username);
	if err != nil {
		// 没有查询到记录
		if err == gorm.ErrRecordNotFound {
			// 对密码进行加密并保存数据
			admin := &model.Admin{
				Username: adminForm.Username,
				Password: util.Sha1(adminForm.Password),
			}

			_, err = this.dao.InsertAdmin(admin)

			return admin, err
		}

	}

	return nil, constant.RECORD_EXISTS
}

//根据ID删除管理员
func (this *AdminService) DeleteAdmin(id uint64) error {

	return this.dao.DeleteAdmin(id)
}

//修改管理员
func (this *AdminService) UpdateAdmin(adminForm *form.AdminForm) (*model.Admin, error) {

	admin := this.dao.GetAdminById(adminForm.Id)

	newAdmin, _ := this.dao.GetAdmin(adminForm.Username)

	//如果用户名不是当前修改的管理员,说明要修改的用户名已经存在了
	if newAdmin.ID != 0 && newAdmin.ID != admin.ID {
		return admin, constant.RECORD_EXISTS
	}
	admin.Username = adminForm.Username
	admin.Password = util.Sha1(adminForm.Password)

	_, err := this.dao.UpdateAdmin(admin)

	return admin, err
}

//根据ID查询管理员
func (this *AdminService) FindAdminById(id uint64) (*model.Admin) {

	admin := this.dao.GetAdminById(id)

	return admin
}

// 查询管理员列表
func (this *AdminService) QueryAdmins(query *form.AdminPageQueryForm) *vo.TableVo {

	result := &vo.TableVo{}
	result.Code = constant.SUCCESS.Code
	result.Msg = constant.SUCCESS.Msg

	size := this.dao.Count()
	result.Total = size

	if size > 0 {
		admins := this.dao.List(query)
		result.Items = admins
	}

	return result

}
